$: << File.expand_path(File.dirname(__FILE__) + '/../')
require "test/unit"

require "nemweb.rb"

class TestNEMwebParser < Test::Unit::TestCase

  def setup
    @csv_string = \
        'C,NEMP.WORLD,DISPATCHSCADA,NEMMCO,PUBLIC,2011/05/23,23:55:08,'\
           '0000000229442072,DISPATCHSCADA,0000000229442066
         I,DISPATCH,UNIT_SCADA,1,SETTLEMENTDATE,DUID,SCADAVALUE
         D,DISPATCH,UNIT_SCADA,1,"2011/05/24 00:00:00",CALL_A_4,20.055
         D,DISPATCH,UNIT_SCADA,1,"2011/05/24 00:00:00",CNUNDAWF,40.451
         C,"END OF REPORT",5'
    @csvreader = NEMwebParser.from_string @csv_string
  end

  def test_table_index_0_not_nil
    assert_not_nil @csvreader.tables[0]
  end

  def test_nemwebtable_headers_meta_and_payload
    table = @csvreader.tables.first
    _test_table_headers(table)
    _test_table_meta(table)
    _test_table_payload(table)
  end

  def test_shortcuts_for_first_table
    _test_table_headers(@csvreader)
    _test_table_meta(@csvreader)
    _test_table_payload(@csvreader)
  end

  def test_table_index_out_of_bounds_is_nil
    assert_nil @csvreader.tables[99]
  end

  def test_access_by_column_name
    table = @csvreader.tables.first
    expected_duid = ['CALL_A_4', 'CNUNDAWF']
    assert_equal(table.duid, expected_duid)
  end


  #------------------------------------------------------- utility functions.
  def _test_table_headers(table)
    expected_headers = [
      'DISPATCH', 'UNIT_SCADA', '1', 'SETTLEMENTDATE',
      'DUID', 'SCADAVALUE']

    assert_equal(expected_headers, table.headers)
  end

  def _test_table_meta(table)
    expected_meta = [
      'NEMP.WORLD', 'DISPATCHSCADA', 'NEMMCO', 'PUBLIC', '2011/05/23',
      '23:55:08', '0000000229442072', 'DISPATCHSCADA', '0000000229442066']

    assert_equal(expected_meta, table.meta)
  end

  def _test_table_payload(table)
    expected_payload = [
      ['DISPATCH','UNIT_SCADA','1','2011/05/24 00:00:00','CALL_A_4','20.055'],
      ['DISPATCH','UNIT_SCADA','1','2011/05/24 00:00:00','CNUNDAWF','40.451']
    ]

    assert_equal(expected_payload, Array(table.payload))
  end
end
